package com.clp.protocol.iec104.connect.state;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 抽象状态：先实现定时任务功能。对于主站和子站都会继承并含有定时任务功能
 */
public abstract class AbstractState implements StateFul {
    /**
     * 定时任务执行器
     */
    private final ScheduledExecutorService scheduledTaskRunner;
    /**
     * 定时任务future
     */
    protected ScheduledFuture<?> scheduledFuture;

    protected AbstractState(ScheduledExecutorService scheduledTaskRunner) {
        this.scheduledTaskRunner = scheduledTaskRunner;
    }

    /**
     * 开启一个定时任务
     * @param task 任务
     * @param initialDelay 延时
     * @param period 周期
     * @param unit 时间单位
     * @return
     */
    protected ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) {
        return scheduledTaskRunner.scheduleAtFixedRate(task, initialDelay, period, unit);
    }

    @Override
    public void tryStopMonitorTask() {
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) scheduledFuture.cancel(true);
    }
}
